package cn.jinjimi.app.main.fragment;

import android.graphics.Typeface;
import android.support.v7.widget.DividerItemDecoration;
import android.support.v7.widget.GridLayoutManager;
import android.text.TextUtils;
import android.text.style.TypefaceSpan;
import android.util.SparseArray;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.TextView;

import java.util.ArrayList;
import java.util.List;

import cn.jinjimi.app.R;
import cn.jinjimi.app.entity.LinkBean;
import cn.jinjimi.app.main.extend.BaseFragment;
import cn.jinjimi.app.main.widget.FrescoImageView.FrescoImageView;
import cn.jinjimi.app.main.widget.XRecyclerView.XRecyclerView;
import cn.jinjimi.app.util.PinyinUtils;
import cn.jinjimi.domain.entity.ProductCategory;
import cn.jinjimi.framework.router.RouterHelper;

/**
 * @author zhenhua
 * @date 2018/5/12
 */

public class ProductBrandFragment extends BaseFragment {
    private XRecyclerView mRecycleview;
    private ProductBrandAdapter mAdapter;
    private ProductCategory mProductCategory;

    public ProductBrandFragment() {
        super();
    }

    @Override
    protected int getLayoutResourceId() {
        return R.layout.fragment_product_brand;
    }

    @Override
    protected void initial() {
        mRecycleview = findView().findViewById(R.id.recyclerview);
        mRecycleview.setPullRefreshEnabled(false);
        mRecycleview.setLayoutManager(new GridLayoutManager(getActivity(), 1));
        mAdapter = new ProductBrandAdapter();
        mRecycleview.setAdapter(mAdapter);
        if (mProductCategory != null) {
            mAdapter.setData(mProductCategory.subs);
        }
    }

    public void setProductCategory(ProductCategory category) {
        mProductCategory = category;
    }


    class BaseViewHolder extends XRecyclerView.ViewHolder {
        public BaseViewHolder(View itemView) {
            super(itemView);
        }
    }

    class BrandViewHolder extends BaseViewHolder {

        private FrescoImageView mImage;
        private TextView mLabel;
        private View mRoot;

        public BrandViewHolder(View itemView) {
            super(itemView);
            init(itemView);
        }

        private void init(View v) {
            mRoot = v;
            mImage = v.findViewById(R.id.image);
            mLabel = v.findViewById(R.id.label);
            v.setOnClickListener(new View.OnClickListener() {
                @Override
                public void onClick(View view) {
                    Object tag = view.getTag();
                    if (tag != null && tag instanceof LinkBean) {
                        RouterHelper.toUrl(getActivity(), ((LinkBean ) tag).link);
                    }
                }
            });
        }

        public void render(LinkBean link) {
            if (link != null) {
                mImage.setPlaceHolderImage(R.drawable.bg_round_border);
                mImage.loadView(link.img);
                mLabel.setTypeface(Typeface.DEFAULT);
                if (!TextUtils.isEmpty(link.img)) {
                    mImage.setVisibility(View.VISIBLE);
                } else if (link.label != null && link.label.length() == 1){
                    mLabel.setTypeface(Typeface.DEFAULT_BOLD);
                    mImage.setVisibility(View.GONE);
                }
                mLabel.setText(link.label);
                mRoot.setTag(link);
            }
        }
    }

    class ProductBrandAdapter extends XRecyclerView.Adapter<BaseViewHolder> {

        private List<LinkBean> mData = new ArrayList<>();
        private SparseArray<List<LinkBean>> mGrouped = new SparseArray<>();

        public void setData(List<LinkBean> list) {
            mData.clear();
            mData.addAll(flat(sortDataWithFirstLetter(list)));
            notifyDataSetChanged();
        }

        @Override
        public BaseViewHolder onCreateViewHolder(ViewGroup parent, int viewType) {
            return new BrandViewHolder(
                LayoutInflater.from(getActivity()).inflate(R.layout.item_brand, parent, false)
            );
        }

        @Override
        public void onBindViewHolder(BaseViewHolder holder, int position) {
            if (holder instanceof BrandViewHolder) {
                ((BrandViewHolder) holder).render(mData.get(position));
            }
        }

        @Override
        public int getItemCount() {
            return mData.size();
        }

        /**
         * 按照用户昵称的首字母分组
         * @param data users
         * @return 按照字母分组
         */
        private SparseArray<List<LinkBean>> sortDataWithFirstLetter(List<LinkBean> data) {
            SparseArray<List<LinkBean>> grouped = new SparseArray<>();
            for (LinkBean link : data) {
                String name = link.label;
                if (TextUtils.isEmpty(name)) {
                    continue;
                }
                String firstLetter = PinyinUtils.getCharacterPinYin(name.charAt(0));
                int index = getIndexOfLetter(firstLetter.toUpperCase());
                if (index < 0 || index > 27) {
                    index = 27;
                }
                List<LinkBean> list = grouped.get(index, new ArrayList<LinkBean>());
                list.add(link);
                grouped.put(index, list);
            }
            return grouped;
        }

        public String[] getKeys() {
            int size = mGrouped != null ? mGrouped.size() : 0;
            String[] keys = new String[size];
            for (int i = 0; i < size; i++) {
                keys[i] = String.valueOf(getLetterOfIndex(mGrouped.keyAt(i)));
            }
            return keys;
        }

        /**
         * 将分好组的用户合并到一个List中用于显示
         * @param grouped
         * @return
         */
        private List<LinkBean> flat(SparseArray<List<LinkBean>> grouped) {
            List<LinkBean> sorted = new ArrayList<>();
            for (int i = 0, len = grouped.size(); i < len; i++) {
                LinkBean letter = new LinkBean();
                letter.label = String.valueOf(getLetterOfIndex(grouped.keyAt(i)));
                sorted.add(letter);
                sorted.addAll(grouped.valueAt(i));
            }
            return sorted;
        }

        /**
         * From 0 to 25
         * @return char
         */
        private char getLetterOfIndex(int index) {
            if (index > 26) {
                return '#';
            }
            return (char) ((int) 'A' + index);
        }

        private int getIndexOfLetter(String letter) {
            int index = 27;
            if (letter != null && letter.length() > 0) {
                index = (int) letter.toUpperCase().charAt(0) - (int) 'A';
                if (index > 26) {
                    index = 27;
                }
            }
            return index;
        }
    }

}
